package drds.plus.executor.cursor.cursor_metadata;

import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;

class ColumnNameAndTableNameAndColumnIndexNextHolderIterator implements Iterator<ColumnNameAndTableNameAndColumnIndexAndNextHolder> {

    Iterator<Map.Entry<String, TableNameAndColumnIndexAndNextHolder>> iterator = null;
    /**
     * 临时iterator 因为可能出现同列名，不同表名的情况
     */
    ColumnNameAndTableNameAndColumnIndexAndNextHolder current = null;

    public ColumnNameAndTableNameAndColumnIndexNextHolderIterator(Map<String/* 列名字 */, TableNameAndColumnIndexAndNextHolder> columnNameToTableNameAndColumnIndexAndNextHolderMap) {
        iterator = columnNameToTableNameAndColumnIndexAndNextHolderMap.entrySet().iterator();
    }

    public boolean hasNext() {
        if (current == null) {
            return iterator.hasNext();//[1]
        } else {
            boolean hasNext = current.getTableNameAndColumnIndexAndNextHolder().next != null;//[2]
            if (!hasNext) {
                current = null;
                hasNext = hasNext();
            }
            return hasNext;
        }
    }

    public ColumnNameAndTableNameAndColumnIndexAndNextHolder next() {
        if (current == null) {
            Map.Entry<String, TableNameAndColumnIndexAndNextHolder> entry = iterator.next();
            if (entry == null) {
                throw new NoSuchElementException();
            } else {
                current = new ColumnNameAndTableNameAndColumnIndexAndNextHolder();
                current.setColumnName(entry.getKey());
                current.setTableNameAndColumnIndexAndNextHolder(entry.getValue());
                return current;
            }
        } else {
            TableNameAndColumnIndexAndNextHolder next = current.getTableNameAndColumnIndexAndNextHolder().next;
            if (next != null) {
                current.setTableNameAndColumnIndexAndNextHolder(next);
                return current;
            } else {
                current = null;
                return next();
            }
        }
    }

    public void remove() {
        throw new IllegalStateException();

    }

}
